<template>
  <div class="index">
    <a-card 
      style="width: 600px;"
      class="index-margin-right-25 index-height-140"
      :title="(orderRateIsMonth ? '本月' : '今日') + '订单数据'"
    >
      <a-icon
        type="sync"
        slot="extra"
        style="color: rgb(24,144,255);cursor: pointer;" 
        @click="transformData('orderRate')"
      />
      <div>
        <span class="index-order-body-top"><b>订单完成率: </b></span>
        <a-progress 
          status="active"
          :percent="orderRateInfo.rate * 100 || 0"
          :strokeWidth="10"
          :strokeColor="'rgb(125, 217, 22)'"
        />
      </div>
      <div style="margin-top: 5px;">
        <span class="index-order-body-top"><b>总订单量: </b>{{orderRateInfo.total || 0}}</span>
        <span class="index-order-body-top" style="text-align: right;"><b>完成订单量: </b>{{orderRateInfo.finish || 0}}</span>
      </div>
    </a-card>
    <a-card
      style="width: 300px;"
      class="index-margin-right-25 index-height-140"
      :title="userWorkerIsMonth ? '本月新增人数' : '今日新增人数'"
    >
      <a-icon
        type="sync"
        slot="extra"
        style="color: rgb(24,144,255);cursor: pointer;" 
        @click="transformData('userWorker')"
      />
      <div class="index-top-center-right index-top-center-right-inner-left">
        <b>会员人数: </b>
        <div style="color: rgb(125, 217, 22);">
          <a-icon type="usergroup-add" />&nbsp;
          <span>{{ userNew > 0 ? `+${userNew}` : `-${userNew}` }}</span>
        </div>
      </div>
      <div class="index-top-center-right">
        <b>员工人数: </b>
        <div style="color: rgb(245, 34, 45);">
          <a-icon type="team" />&nbsp;
          <span>{{ workerNew > 0 ? `+${workerNew}` : `-${workerNew}` }}</span>
        </div>
      </div>
    </a-card>
    <a-card
      style="width: 300px;"
      class="index-height-140" 
      :title="evaluationIsMonth ? '本月评价情况' : '今日评价情况'">
      <a-icon
        type="sync"
        slot="extra"
        style="color: rgb(24,144,255);cursor: pointer;" 
        @click="transformData('evaluation')"
      />
      <div class="index-top-center-right index-top-center-right-inner-left">
        <b>好评率: </b>
        <div style="color: rgb(125, 217, 22);">
          <a-icon type="smile" />&nbsp;
          <span>{{ goodRate * 100 }}%</span>
        </div>
      </div>
      <div class="index-top-center-right">
        <b>差评率: </b>
        <div style="color: rgb(245, 34, 45);">
          <a-icon type="frown" />&nbsp;
          <span>{{ badRate * 100 }}%</span>
        </div>
      </div>
    </a-card>
    <br><br>
    <a-card style="width: 800px;"
            class="index-margin-right-25 index-height-340"
            :title="orderCountIsMonth ? '订单交易量（月）' : '订单交易量（周）'">
      <a-icon
        type="sync"
        slot="extra"
        style="color: rgb(24,144,255);cursor: pointer;" 
        @click="transformData('orderCount')"
      />
      <div id="order-change" style="width: 100%;height: 100%;"></div>
    </a-card>
    <a-card style="width: 425px;"
            class="index-height-340"
            title="员工业绩排名">
      <a slot="extra" @click="goToWorkerPage">查看更多</a>
      <div class="index-worker">
        <div class="index-worker-score"
             :class="isScore === true ? 'active' : ''"
             style="margin-right: 8px;"
             @click="getWorkerListInfoByScore">按业绩排名</div>
        <div class="index-worker-score"
             :class="isScore === false ? 'active' : ''"
             @click="getWorkerListInfoByBenefit">按盈利排名</div>
      </div>
      <a-spin style="width: 100%;height: calc(100% - 48px);overflow-y: auto;"
              tip="正在加载数据，请稍后..."
              :spinning="spinning">
        <div class="index-worker-detail">
          <a-empty style="margin-top: 30px;"
                   v-if="(isScore && workerScoreRanking.length === 0) || (!isScore && workerBenefitRanking.length === 0)"></a-empty>
          <div v-for="(item, i) in isScore ? workerScoreRanking : workerBenefitRanking"
               :key="i"
               style="margin: 4px 0;"
               v-else>
          <span class="index-worker-detail-rank"
                :class="i === 0 ? 'index-worker-detail-golden' : i === 1 ? 'index-worker-detail-sliver' : i === 2 ? 'index-worker-detail-coppery' : ''">
            {{i + 1}}
          </span>
            <a-avatar size="large"
                      style="vertical-align: top;margin-right: 6px;background-color: rgb(190,200,200);" >
              {{item.name[0]}}
            </a-avatar>
            <span style="vertical-align: top;width: 90px;">
            <div>{{item.name}}</div>
            <div>{{item.repairType}}</div>
          </span>
            <span> <b>{{item.phone}}</b></span>
            <span>本月{{isScore ? '完成' : '盈利'}} <b>{{isScore ? item.finish: transformToFixed(item.benefit, 2)}}</b>{{isScore ? '单' : '元'}}</span>
          </div>
        </div>
      </a-spin>
    </a-card>
    <br><br>
    <a-card style="width: 1250px;"
            class="index-height-340" title="总分析图">
      <div id="total-analysis" style="width: 100%;height: 100%;"></div>
    </a-card>
  </div>
</template>

<script>
import {
  getWorkerListByFinish, 
  getWorkerListByBenefit,
  getOrderFinishRate,
  getUserAddCount,
  getOrderEvaRate,
  getOrderDealCount
} from '@/api/api';

  export default {
    name: "Index",
    data() {
      return {
        orderRateInfo: {},
        isScore: true,
        workerScoreRanking: [],
        workerBenefitRanking: [],
        workerData: [],
        spinning: true,
        currentWeek: [],
        orderChangeSeries: [],
        orderChangeData: [],
        orderChangeDataDetail: [],
        totalAnalysisData: [],
        totalAnalysisSeries: [],
        orderRateIsMonth: false,
        userNew: 0,
        workerNew: 0,
        userWorkerIsMonth: false,
        evaluationIsMonth: false,
        goodRate: 0,
        badRate: 0,
        orderCountIsMonth: false,
      }
    },
    methods: {
      /**
       * 将数据变为保留n位小数
       */
      transformToFixed(data, n) {
        return data.toFixed(n);
      },
      /**
       * 切换本月和今日数据
       */
      transformData(data) {
        switch (data) {
          case 'orderRate': 
            this.orderRateIsMonth = !this.orderRateIsMonth;
            this.getOrderFinishRate();
            break;
          case 'userWorker': 
            this.userWorkerIsMonth = !this.userWorkerIsMonth;
            this.getUserAddCountData();
            break;
          case 'evaluation': 
            this.evaluationIsMonth = !this.evaluationIsMonth;
            this.getOrderEvaRateData();
            break;
          case 'orderCount':
            this.orderCountIsMonth = !this.orderCountIsMonth;
            this.getOrderDealCountData();
            break;
        }
      },
      /**
       * 获取完成订单数据
       */
      getOrderFinishRate() {
        getOrderFinishRate({ isMonth: this.orderRateIsMonth })
          .then(res => {
            this.orderRateInfo = res.data;
          })
          .catch(err => {
            this.$message.error(`获取订单完成数据失败，${err.data}`);
          })
      },
      /**
       * 获取新增用户数
       */
      getUserAddCountData() {
        getUserAddCount({ isMonth: this.userWorkerIsMonth })
          .then(res => {
            this.userNew = res.data.userCount;
            this.workerNew = res.data.workerCount;
          })
          .catch(err => {
            this.$message.error(`获取新增用户员工数量失败，${err.data}`);
          })
      },
      /**
       * 获取订单好差评率
       */
      getOrderEvaRateData() {
        getOrderEvaRate({ isMonth: this.evaluationIsMonth })
          .then(res => {
            this.goodRate = res.data.goodRate;
            this.badRate = res.data.badRate;
          })
          .catch(err => {
            this.$message.error(`获取评价情况失败，${err.data}`);
          })
      },
      /**
       * 加载图表
       */
      loadOrderChange(orderCountLegend, orderCountX, orderChangeSeries) {
        try {
          let myCharts = this.$echarts.init(document.getElementById('order-change'));
          let options = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
              }
            },
            legend: {
              data: orderCountLegend,
            },
            grid: {
              left: '3%',
              right: '6%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [
              {
                type: 'category',
                name: '时间',
                data: orderCountX,
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '数量'
              }
            ],
            series: orderChangeSeries,
          };
          myCharts.setOption(options);
        } catch (error) {
          console.log(error);
        }
      },
      /**
       * 加载图表
       */
      loadTotalAnalysis() {
        let myChartsAnalysis = this.$echarts.init(document.getElementById('total-analysis'));
        let options = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: this.totalAnalysisData,
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: this.currentWeek,
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: this.totalAnalysisSeries,
        };
        myChartsAnalysis.setOption(options);
      },
      /**
       * 加载维修工按业绩排名数据
       */
      getWorkerListInfoByScore() {
        this.isScore = true;
        this.spinning = true;
        getWorkerListByFinish()
          .then(res => {
            let dataArray = res.data.list;
            this.workerScoreRanking = dataArray;
          })
          .catch(err => {
            this.$message.error(err);
          })
          .finally(() => {
            this.spinning = false;
          })
      },
      /**
       * 加载维修工按盈利排名数据
       */
      getWorkerListInfoByBenefit() {
        this.isScore = false;
        this.spinning = true;
        getWorkerListByBenefit()
        .then(res => {
            let dataArray = res.data.list;
            this.workerBenefitRanking = dataArray;
          })
          .catch(err => {
            this.$message.error(err.data);
          })
          .finally(() => {
            this.spinning = false;
          })
      },
      /**
       * 跳转至worker页面
       */
      goToWorkerPage() {
        this.$router.push('/home/worker-list');
        this.$store.commit('setCurRouter', '/home/worker-list');
      },
      /**
       * 获取订单统计
       */
      getOrderDealCountData() {
        getOrderDealCount({ isMonth: this.orderCountIsMonth })
          .then(res => {
            let orderCountLegend = [], orderCountX = [], orderCountY = [];
            res.data[0].data.forEach(item => {
              orderCountLegend.push(item.work);
            });
            orderCountX = res.data.map(item => {
              return item.time;
            });
            for (let z = 0; z < orderCountLegend.length; z++) {
              let curData = [];
              for (let i = 0; i < res.data.length; i++) {
                for (let j = 0; j < res.data[i].data.length; j++) {
                  if (res.data[i].data[j].work === orderCountLegend[z]) {
                    curData.push(res.data[i].data[j].count)
                  }
                }
              }
              orderCountY.push({
                name: orderCountLegend[z],
                type: 'line', 
                smooth: 'true', 
                data: curData,
              })
            }
            // orderCountY = [
            //   {name: '冰箱空调类', type: 'line', smooth: 'true', data: [1,0,0,0,1,0,1]},
            //   {name: '洗衣机类', type: 'line', smooth: 'true', data: [0,0,2,0,1,0,1]},
            //   {name: '电视机类', type: 'line', smooth: 'true', data: [0,2,0,0,1,0,1]},
            //   {name: '电子设备类', type: 'line', smooth: 'true', data: [3,0,0,0,1,0,1]},
            //   {name: '基础设施类', type: 'line', smooth: 'true', data: [0,0,0,3,1,0,1]},
            //   {name: '全部', type: 'line', smooth: 'true', data: [0,0,0,0,1,0,1]},
            // ];
            this.loadOrderChange(orderCountLegend, orderCountX, orderCountY);
          })
          .catch(err => {
            this.$message.error(err.data);
          });
      }
    },
    mounted() {
      this.getWorkerListInfoByScore();
      this.getOrderFinishRate();
      this.getUserAddCountData();
      this.getOrderEvaRateData();
      this.getOrderDealCountData();
    },
  }
</script>

<style lang="scss">
.index {
  width: 1270px;
  overflow-x: auto;
  .ant-card {
    display: inline-block;
    vertical-align: middle;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  .ant-card-head {
    min-height: 36px;
  }
  .ant-card-body {
    padding: 12px;
    height: calc(100% - 36px);
  }
  .ant-card-head-title {
    padding: 6px 0;
    font-weight: 600;
  }
  .ant-card-extra {
    padding: 6px 0;
  }
  .index-margin-right-25 {
    margin-right: 25px;
  }
  .index-height-140 {
    height: 140px;
  }
  .index-height-340 {
    height: 340px;
  }
  .index-order-body-top {
    width: 50%;
    display: inline-block;
    font-size: 17px;
    b {
      font-size: 15px;
    }
  }
  .index-top-center-right {
    width: 50%;
    height: 100%;
    display: inline-block;
    box-sizing: border-box;
    padding: 0 4px 4px 4px;
    b {
      font-size: 15px;
    }
    div {
      text-align: center;
      height: calc(100% - 20px);
      line-height: 50px;
      font-size: 24px;
    }
  }
  .index-top-center-right-inner-left {
    border-right: 2px solid #ddd;
    vertical-align: top;
  }
  .index-worker {
    width: 90%;
    margin-left: 5%;
    padding: 4px;
    background-color: #eeeeee;
    height: 38px;
    border-radius: 6px;
    .index-worker-score {
      display: inline-block;
      width: calc(50% - 4px);
      height: 100%;
      border-radius: 6px;
      text-align: center;
      line-height: 30px;
      font-weight: 600;
      letter-spacing: 2px;
      cursor: pointer;
    }
    .active {
      background-color: #ffffff;
      color: rgb(39, 159, 222);
    }
  }
  .index-worker-detail {
    width: 100%;
    box-sizing: border-box;
    margin: 6px 0;
    padding: 4px;
    .index-worker-detail-rank {
      display: inline-block;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      line-height: 19px;
      text-align: center;
      font-weight: bold;
      margin-right: 2px;
      margin-top: 14px;;
      vertical-align: top;
    }
    .index-worker-detail-golden {
      color: #ffffff;
      background-color: #ffb100;
    }
    .index-worker-detail-sliver {
      color: #ffffff;
      background-color: #A4A4A4;
    }
    .index-worker-detail-coppery {
      color: #ffffff;
      background-color: #a86f00;
    }
    span {
      display: inline-block;
      font-size: 14px;
      height: 40px;
      line-height: 40px;
      div {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      div:first-child {
        height: 24px;
        font-size: 17px;
        line-height: 24px;
      }
      div:last-child {
        height: 16px;
        font-size: 12px;
        line-height: 16px;
      }
    }
    span:last-child {
      float: right;
      padding-right: 3px;
    }
  }
}
</style>